package com.maidada.codesharebackend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.maidada.codesharebackend.common.PageResult;
import com.maidada.codesharebackend.common.ThrowUtils;
import com.maidada.codesharebackend.exception.GlobalErrorCode;
import com.maidada.codesharebackend.mapper.TagMapper;
import com.maidada.codesharebackend.model.dto.tag.TagAddRequest;
import com.maidada.codesharebackend.model.dto.tag.TagQueryRequest;
import com.maidada.codesharebackend.model.dto.tag.TagUpdateRequest;
import com.maidada.codesharebackend.model.entity.Tag;
import com.maidada.codesharebackend.model.vo.TagVO;
import com.maidada.codesharebackend.service.TagService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 标签表 Service 实现类
 *
 * @author wulinxuan
 */
@Service
public class TagServiceImpl extends ServiceImpl<TagMapper, Tag> implements TagService {

    @Override
    public Long addTag(TagAddRequest tagAddRequest) {
        String name = tagAddRequest.getName();

        // 校验标签名是否已存在
        LambdaQueryWrapper<Tag> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Tag::getName, name);
        long count = this.count(wrapper);
        ThrowUtils.throwIf(count > 0, GlobalErrorCode.DATA_ALREADY_EXISTS_ERROR, "标签名已存在");

        // 创建标签
        Tag tag = BeanUtil.copyProperties(tagAddRequest, Tag.class);

        boolean result = this.save(tag);
        ThrowUtils.throwIf(!result, GlobalErrorCode.OPERATION_ERROR, "新增标签失败");

        return tag.getId();
    }

    @Override
    public Boolean deleteTag(Long id) {
        ThrowUtils.throwIf(id == null || id <= 0, GlobalErrorCode.PARAMS_ERROR, "标签id不能为空");

        // 校验标签是否存在
        Tag tag = this.getById(id);
        ThrowUtils.throwIf(tag == null, GlobalErrorCode.DATA_NOT_FOUND_ERROR, "标签不存在");

        boolean result = this.removeById(id);
        ThrowUtils.throwIf(!result, GlobalErrorCode.OPERATION_ERROR, "删除标签失败");

        return true;
    }

    @Override
    public Boolean updateTag(TagUpdateRequest tagUpdateRequest) {
        Long id = tagUpdateRequest.getId();
        ThrowUtils.throwIf(id == null || id <= 0, GlobalErrorCode.PARAMS_ERROR, "标签id不能为空");

        // 校验标签是否存在
        Tag tag = this.getById(id);
        ThrowUtils.throwIf(tag == null, GlobalErrorCode.DATA_NOT_FOUND_ERROR, "标签不存在");

        // 如果修改了标签名，校验标签名是否已存在
        if (StrUtil.isNotBlank(tagUpdateRequest.getName()) && !tagUpdateRequest.getName().equals(tag.getName())) {
            LambdaQueryWrapper<Tag> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Tag::getName, tagUpdateRequest.getName());
            long count = this.count(wrapper);
            ThrowUtils.throwIf(count > 0, GlobalErrorCode.DATA_ALREADY_EXISTS_ERROR, "标签名已存在");
        }

        // 更新标签
        Tag updateTag = BeanUtil.copyProperties(tagUpdateRequest, Tag.class);
        boolean result = this.updateById(updateTag);
        ThrowUtils.throwIf(!result, GlobalErrorCode.OPERATION_ERROR, "修改标签失败");

        return true;
    }

    @Override
    public PageResult<TagVO> pageTag(TagQueryRequest tagQueryRequest) {
        // 构建查询条件
        LambdaQueryWrapper<Tag> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(tagQueryRequest.getId() != null, Tag::getId, tagQueryRequest.getId())
                .eq(tagQueryRequest.getParentId() != null, Tag::getParentId, tagQueryRequest.getParentId())
                .like(StrUtil.isNotBlank(tagQueryRequest.getName()), Tag::getName, tagQueryRequest.getName())
                .orderByDesc(Tag::getCreateTime);

        // 分页查询
        Page<Tag> page = new Page<>(tagQueryRequest.getPageNo(), tagQueryRequest.getPageSize());
        Page<Tag> tagPage = this.page(page, wrapper);

        // 转换为VO
        List<TagVO> tagVOList = tagPage.getRecords().stream()
                .map(tag -> BeanUtil.copyProperties(tag, TagVO.class))
                .collect(Collectors.toList());

        return new PageResult<>(tagVOList, tagPage.getTotal());
    }

    @Override
    public TagVO getTagById(Long id) {
        ThrowUtils.throwIf(id == null || id <= 0, GlobalErrorCode.PARAMS_ERROR, "标签id不能为空");

        Tag tag = this.getById(id);
        ThrowUtils.throwIf(tag == null, GlobalErrorCode.DATA_NOT_FOUND_ERROR, "标签不存在");

        return BeanUtil.copyProperties(tag, TagVO.class);
    }
}

